from flask import Flask, render_template, request, redirect, url_for, jsonify
import sqlite3
from datetime import datetime
import os

app = Flask(__name__)

# 数据库初始化
def init_db():
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    
    # 创建文章表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS articles (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    
    # 创建评论表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS comments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            article_id INTEGER NOT NULL,
            author TEXT NOT NULL,
            content TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (article_id) REFERENCES articles (id) ON DELETE CASCADE
        )
    ''')
    
    conn.commit()
    conn.close()

# 首页 - 文章列表
@app.route('/')
def index():
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, title, content, created_at FROM articles ORDER BY created_at DESC')
    articles = cursor.fetchall()
    conn.close()
    
    # 截取文章摘要
    articles = [(id, title, content[:200] + '...' if len(content) > 200 else content, created_at) 
                  for id, title, content, created_at in articles]
    
    return render_template('index.html', articles=articles)

# 文章详情页
@app.route('/article/<int:article_id>')
def article_detail(article_id):
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    
    # 获取文章
    cursor.execute('SELECT id, title, content, created_at FROM articles WHERE id = ?', (article_id,))
    article = cursor.fetchone()
    
    if not article:
        conn.close()
        return "文章不存在", 404
    
    # 获取评论
    cursor.execute('SELECT author, content, created_at FROM comments WHERE article_id = ? ORDER BY created_at ASC', (article_id,))
    comments = cursor.fetchall()
    
    conn.close()
    
    return render_template('article.html', article=article, comments=comments)

# 添加评论
@app.route('/add_comment/<int:article_id>', methods=['POST'])
def add_comment(article_id):
    author = request.form.get('author', '').strip()
    content = request.form.get('content', '').strip()
    
    if not author or not content:
        return "作者和评论内容不能为空", 400
    
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    
    # 检查文章是否存在
    cursor.execute('SELECT id FROM articles WHERE id = ?', (article_id,))
    if not cursor.fetchone():
        conn.close()
        return "文章不存在", 404
    
    # 添加评论
    cursor.execute('INSERT INTO comments (article_id, author, content) VALUES (?, ?, ?)', 
                   (article_id, author, content))
    
    conn.commit()
    conn.close()
    
    return redirect(url_for('article_detail', article_id=article_id))

# 管理页面
@app.route('/admin')
def admin():
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, title, content, created_at FROM articles ORDER BY created_at DESC')
    articles = cursor.fetchall()
    conn.close()
    
    return render_template('admin.html', articles=articles)

# 添加文章
@app.route('/add_article', methods=['POST'])
def add_article():
    title = request.form.get('title', '').strip()
    content = request.form.get('content', '').strip()
    
    if not title or not content:
        return "标题和内容不能为空", 400
    
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO articles (title, content) VALUES (?, ?)', (title, content))
    conn.commit()
    conn.close()
    
    return redirect(url_for('admin'))

# 编辑文章
@app.route('/edit_article/<int:article_id>', methods=['POST'])
def edit_article(article_id):
    title = request.form.get('title', '').strip()
    content = request.form.get('content', '').strip()
    
    if not title or not content:
        return "标题和内容不能为空", 400
    
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE articles SET title = ?, content = ? WHERE id = ?', 
                   (title, content, article_id))
    conn.commit()
    conn.close()
    
    return redirect(url_for('admin'))

# 删除文章
@app.route('/delete_article/<int:article_id>', methods=['POST'])
def delete_article(article_id):
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    cursor.execute('DELETE FROM articles WHERE id = ?', (article_id,))
    conn.commit()
    conn.close()
    
    return redirect(url_for('admin'))

if __name__ == '__main__':
    init_db()
    app.run(debug=True, host='0.0.0.0', port=5000)
